# -*- coding: utf-8 -*-
# frontend/pages/analytics.py
"""
数据分析页面
"""

import streamlit as st
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
from datetime import datetime, timedelta
from frontend.utils.ui_helpers import create_usage_chart, create_conversation_timeline

def render_analytics_page():
    """渲染数据分析页面"""
    
    st.markdown("## 📊 数据分析仪表板")
    
    # 检查是否有数据
    if not st.session_state.get("chat_history"):
        st.info("📈 暂无对话数据，开始聊天后这里将显示详细的使用统计")
        return
    
    # 分析标签页
    tab1, tab2, tab3, tab4 = st.tabs(["📈 使用概览", "🤖 模型分析", "💬 对话分析", "📊 趋势分析"])
    
    with tab1:
        render_usage_overview()
    
    with tab2:
        render_model_analysis()
    
    with tab3:
        render_conversation_analysis()
    
    with tab4:
        render_trend_analysis()

def render_usage_overview():
    """渲染使用概览"""
    st.markdown("### 📈 使用概览")
    
    # 获取基础统计数据
    chat_history = st.session_state.get("chat_history", [])
    
    user_messages = [msg for msg in chat_history if msg["role"] == "user"]
    ai_messages = [msg for msg in chat_history if msg["role"] == "assistant"]
    
    # 关键指标卡片
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric(
            "总对话轮数",
            len(user_messages),
            delta=f"+{len(user_messages)} 本次会话"
        )
    
    with col2:
        avg_length = sum(len(msg["content"]) for msg in user_messages) / max(len(user_messages), 1)
        st.metric(
            "平均问题长度",
            f"{avg_length:.0f} 字符",
            delta="📝"
        )
    
    with col3:
        total_ai_chars = sum(len(msg["content"]) for msg in ai_messages)
        st.metric(
            "AI回答总字数",
            f"{total_ai_chars:,} 字符",
            delta="🤖"
        )
    
    with col4:
        if ai_messages:
            avg_response_length = total_ai_chars / len(ai_messages)
            st.metric(
                "平均回答长度",
                f"{avg_response_length:.0f} 字符",
                delta="📏"
            )
    
    # 使用时间分布
    st.markdown("---")
    st.markdown("### ⏰ 使用时间分布")
    
    if user_messages:
        # 创建时间数据（模拟）
        hours = [datetime.now().hour + i % 24 for i in range(len(user_messages))]
        hour_counts = pd.Series(hours).value_counts().sort_index()
        
        fig = px.bar(
            x=hour_counts.index,
            y=hour_counts.values,
            title="一天中的使用时间分布",
            labels={"x": "小时", "y": "对话次数"}
        )
        fig.update_layout(height=400)
        st.plotly_chart(fig, use_container_width=True)
    
    # 对话长度分布
    col1, col2 = st.columns(2)
    
    with col1:
        if user_messages:
            question_lengths = [len(msg["content"]) for msg in user_messages]
            fig = px.histogram(
                x=question_lengths,
                title="用户问题长度分布",
                labels={"x": "字符数", "y": "频次"},
                nbins=20
            )
            fig.update_layout(height=300)
            st.plotly_chart(fig, use_container_width=True)
    
    with col2:
        if ai_messages:
            answer_lengths = [len(msg["content"]) for msg in ai_messages]
            fig = px.histogram(
                x=answer_lengths,
                title="AI回答长度分布",
                labels={"x": "字符数", "y": "频次"},
                nbins=20
            )
            fig.update_layout(height=300)
            st.plotly_chart(fig, use_container_width=True)

def render_model_analysis():
    """渲染模型分析"""
    st.markdown("### 🤖 AI模型使用分析")
    
    ai_messages = [msg for msg in st.session_state.get("chat_history", []) if msg["role"] == "assistant"]
    
    if not ai_messages:
        st.info("暂无AI响应数据")
        return
    
    # 统计各模型使用次数
    model_usage = {}
    for msg in ai_messages:
        models = msg.get("models", ["unknown"])
        for model in models:
            model_usage[model] = model_usage.get(model, 0) + 1
    
    # 模型使用分布饼图
    col1, col2 = st.columns(2)
    
    with col1:
        if model_usage:
            fig = create_usage_chart(model_usage)
            st.plotly_chart(fig, use_container_width=True)
    
    with col2:
        # 模型性能对比表
        st.markdown("#### 📊 模型性能对比")
        
        performance_data = []
        for model, count in model_usage.items():
            # 计算该模型的平均响应长度
            model_messages = [msg for msg in ai_messages if model in msg.get("models", [])]
            avg_length = sum(len(msg["content"]) for msg in model_messages) / len(model_messages)
            
            performance_data.append({
                "模型": model,
                "使用次数": count,
                "使用占比": f"{count/len(ai_messages)*100:.1f}%",
                "平均回答长度": f"{avg_length:.0f} 字符"
            })
        
        df = pd.DataFrame(performance_data)
        st.dataframe(df, use_container_width=True, hide_index=True)
    
    # 模型回答质量分析（模拟数据）
    st.markdown("---")
    st.markdown("#### 🎯 模型特性分析")
    
    model_characteristics = {
        "gpt-4": {"创意性": 9, "准确性": 9, "逻辑性": 8, "友好性": 8},
        "gpt-3.5-turbo": {"创意性": 7, "准确性": 8, "逻辑性": 8, "友好性": 9},
        "claude-3": {"创意性": 8, "准确性": 9, "逻辑性": 9, "友好性": 7},
    }
    
    if any(model in model_usage for model in model_characteristics.keys()):
        # 雷达图
        categories = ["创意性", "准确性", "逻辑性", "友好性"]
        
        fig = go.Figure()
        
        for model, scores in model_characteristics.items():
            if model in model_usage:
                fig.add_trace(go.Scatterpolar(
                    r=list(scores.values()),
                    theta=categories,
                    fill='toself',
                    name=model
                ))
        
        fig.update_layout(
            polar=dict(
                radialaxis=dict(
                    visible=True,
                    range=[0, 10]
                )),
            showlegend=True,
            title="AI模型特性对比",
            height=500
        )
        
        st.plotly_chart(fig, use_container_width=True)

def render_conversation_analysis():
    """渲染对话分析"""
    st.markdown("### 💬 对话内容分析")
    
    chat_history = st.session_state.get("chat_history", [])
    user_messages = [msg for msg in chat_history if msg["role"] == "user"]
    
    if not user_messages:
        st.info("暂无对话数据")
        return
    
    # 问题类型分析（基于关键词）
    st.markdown("#### 🏷️ 问题类型分析")
    
    categories = {
        "技术问题": ["代码", "编程", "算法", "技术", "开发", "bug", "error"],
        "学习问题": ["学习", "教程", "解释", "什么是", "如何", "怎么"],
        "创意问题": ["创意", "想法", "设计", "方案", "策划", "建议"],
        "生活问题": ["生活", "健康", "饮食", "运动", "旅游", "娱乐"],
        "工作问题": ["工作", "职业", "管理", "团队", "项目", "效率"]
    }
    
    category_counts = {cat: 0 for cat in categories.keys()}
    
    for msg in user_messages:
        content = msg["content"].lower()
        for category, keywords in categories.items():
            if any(keyword in content for keyword in keywords):
                category_counts[category] += 1
                break
    
    # 问题类型分布
    col1, col2 = st.columns(2)
    
    with col1:
        if any(count > 0 for count in category_counts.values()):
            fig = px.pie(
                values=list(category_counts.values()),
                names=list(category_counts.keys()),
                title="问题类型分布"
            )
            st.plotly_chart(fig, use_container_width=True)
    
    with col2:
        # 高频词汇分析
        st.markdown("#### 🔤 高频词汇")
        
        all_text = " ".join([msg["content"] for msg in user_messages])
        # 简单的词频统计（实际项目中可以使用jieba等库）
        words = all_text.split()
        word_freq = {}
        
        for word in words:
            if len(word) > 1:  # 过滤单字符
                word_freq[word] = word_freq.get(word, 0) + 1
        
        # 取前10个高频词
        top_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)[:10]
        
        if top_words:
            words_df = pd.DataFrame(top_words, columns=["词汇", "频次"])
            st.dataframe(words_df, use_container_width=True, hide_index=True)
    
    # 对话质量评分（模拟）
    st.markdown("---")
    st.markdown("#### ⭐ 对话质量评估")
    
    col1, col2, col3 = st.columns(3)
    
    with col1:
        # 用户满意度（模拟）
        satisfaction = 4.2
        st.metric("用户满意度", f"{satisfaction}/5.0", "⭐" * int(satisfaction))
    
    with col2:
        # 回答准确性（模拟）
        accuracy = 87
        st.metric("回答准确性", f"{accuracy}%", "🎯")
    
    with col3:
        # 响应速度（模拟）
        avg_response_time = 2.3
        st.metric("平均响应时间", f"{avg_response_time}秒", "⚡")

def render_trend_analysis():
    """渲染趋势分析"""
    st.markdown("### 📊 使用趋势分析")
    
    # 模拟趋势数据
    dates = pd.date_range(start="2024-01-01", end=datetime.now(), freq="D")
    conversations_per_day = pd.Series(
        data=np.random.poisson(5, len(dates)),
        index=dates
    )
    
    # 每日对话趋势
    fig = px.line(
        x=conversations_per_day.index,
        y=conversations_per_day.values,
        title="每日对话数量趋势",
        labels={"x": "日期", "y": "对话数量"}
    )
    fig.update_layout(height=400)
    st.plotly_chart(fig, use_container_width=True)
    
    # 预测未来趋势（简单线性预测）
    st.markdown("#### 🔮 使用趋势预测")
    
    # 简单的趋势预测
    recent_avg = conversations_per_day.tail(7).mean()
    prediction_text = "📈 增长趋势" if recent_avg > conversations_per_day.mean() else "📉 平稳趋势"
    
    col1, col2 = st.columns(2)
    
    with col1:
        st.info(f"当前趋势: {prediction_text}")
        st.markdown(f"- 7日平均: {recent_avg:.1f} 次/天")
        st.markdown(f"- 总体平均: {conversations_per_day.mean():.1f} 次/天")
    
    with col2:
        # 使用热力图显示一周内的活跃时间
        weekday_activity = pd.DataFrame({
            "星期": ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
            "活跃度": [8, 7, 6, 8, 9, 5, 4]
        })
        
        fig = px.bar(
            weekday_activity,
            x="星期",
            y="活跃度",
            title="一周活跃度分布"
        )
        fig.update_layout(height=300)
        st.plotly_chart(fig, use_container_width=True)
